package com.wsc.personalblog.security.Exception;

import com.alibaba.fastjson.JSON;
import com.wsc.personalblog.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权异常处理
 */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Result<String> failed = Result.failed("没有权限");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        response.setStatus(403);
        String requestURI = request.getRequestURI();
        log.error(requestURI+"没有权限");
        String jsonString = JSON.toJSONString(failed);
        response.getWriter().write(jsonString);
    }
}
